﻿using Abp.Domain.Entities;
using System;
using System.IO;

namespace Batman.Jianbei.Forum.Core.Domains.Posts
{
    public class PostImg : Entity<string>
    {
        /// <summary>
        /// 归属帖子
        /// </summary>
        public string PostId { get; set; }

        public Post Post { get; set; }

        /// <summary>
        /// 图片地址
        /// </summary>
        public string Img { get; set; }

        /// <summary>
        /// 是否删除
        /// </summary>
        public bool IsDeleted { get; set; }

        public PostImg() { }

        public PostImg(MemoryStream mm)
        {
            DateTime now = DateTime.Now;
            Img = NewRelativeFile();
            string full_file_name = $"wwwroot/" + Img;

            FileInfo fileInfo = new FileInfo(full_file_name);
            if (!Directory.Exists(fileInfo.Directory.FullName))
                Directory.CreateDirectory(fileInfo.Directory.FullName);

            File.WriteAllBytes(full_file_name, mm.ToArray());
        }

        /// <summary>
        /// 创建出新的相对图片保存地址,结果保存于
        /// </summary>
        /// <returns>格式 yyyy/MM/MMDD/GUID.jpg,例如与： 2019/04/0413/55737ca4-5dc7-11e9-84d0-0242ac120002.jpg</returns>
        public static string NewRelativeFile()
        {
            DateTime now = DateTime.Now;
            string relative_path_name = $"images/{now.ToString("yyyy")}/{now.ToString("MM")}/{now.ToString("MMdd")}/{ Guid.NewGuid().ToString()}.jpg";
            return relative_path_name;
        }
    }
}
